package com.bmps.springcloud.insuredmicroservice.service.rabbitmq.production;

import com.bmps.springcloud.insuredmicroservice.model.rabbitmq.PolicyDataEx;
import com.bmps.springcloud.insuredmicroservice.service.accept.InsuranceAcceptService;
import com.bmps.springcloud.insuredmicroservice.util.amqp.DateUtils;
import com.bmps.springcloud.insuredmicroservice.util.mail.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description: 如果消息没有到exchange,则confirm回调,ack=false
 *               如果消息到达exchange,则confirm回调,ack=true
 * @author: lazasha
 * @date: 2019/12/24  13:28
 **/
@Service
public class AcceptConfirmCallback implements RabbitTemplate.ConfirmCallback {
    private final Logger logger = LoggerFactory.getLogger(AcceptConfirmCallback.class);
    
    private final InsuranceAcceptService insuranceAcceptService;
    private final MailUtil mailUtil;

    public AcceptConfirmCallback(InsuranceAcceptService insuranceAcceptService, MailUtil mailUtil) {
        this.insuranceAcceptService = insuranceAcceptService;
        this.mailUtil = mailUtil;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        PolicyDataEx dataEx = (PolicyDataEx) correlationData;
        assert dataEx != null;
        String contno = dataEx.getId();
        if (b) {
            logger.info("消息发送成功:\n"
                    + "返回时间: " + DateUtils.localDateTimeToString(LocalDateTime.now())
                    + ",保单号: " +  contno
                    + ",发送消息: " + dataEx.getMessage());
        } else {
            logger.info("消息发送失败,未路由到交换机:\n"
                    + "返回时间: " + DateUtils.localDateTimeToString(LocalDateTime.now())
                    + ",发送消息: " + dataEx.getMessage()
                    + ",保单号: " + contno
                    + ",失败原因: " + s);
            //更新数据库，让批处理来处理为发送成功的消息
            // 发送邮件，通知mq发送消息失败
//            mailUtil.sendMail("消息生产者发送消息失败","消息发送失败,未路由到交换机:\n"
//                    + "【返回时间: 】" + DateUtils.localDateTimeToString(LocalDateTime.now())
//                    + "【,发送消息:】 " + dataEx.getMessage()
//                    + "【,保单号: 】" + contno
//                    + ",【失败原因:】 " + s);
            try {
                insuranceAcceptService.updateAcceptPushFlag(0, contno, 4);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("系统异常，异常信息为：" + e.getMessage());
            }
        }
    }
}
